<template>
  <div class="chart-wrapper" v-loading="loading">
    <BaseChart v-if="chartOption" ref="baseChartRef" :options="chartOption" />
  </div>
</template>

<script setup>
import { useCompanyStore } from "@/stores/company";
import BaseChart from "./BaseChart.vue";
import {
  getFirstLevelMeterList,
  getMeterInfoApi,
  getMeterReportApi,
} from "@/api/meter";
import { computed, ref, watchEffect } from "vue";
import { handleError } from "@/utils/handleError";
import dayjs from "dayjs";
import { processArrays } from "@/utils/meterUtils";

const props = defineProps({
  chartType: {
    type: String,
    default: "bar",
  },
  meterType: {
    type: String,
    default: "water",
  },
  meterId: {
    type: Number,
    default: null,
  },
  interval: {
    type: String,
    default: "half_hour",
  },
  dateRange: {
    type: Array,
    default: () => [
      {
        legend: "前日",
        start_time: dayjs().subtract(2, "day").startOf("day").valueOf(),
        end_time: dayjs().subtract(1, "day").startOf("day").valueOf(),
      },
      {
        legend: "昨日",
        start_time: dayjs().subtract(1, "day").valueOf(),
        end_time: dayjs().startOf("day").valueOf(),
      },
    ],
  },
});

let chartOption = ref({});
const loading = ref(false);
let companyStore = useCompanyStore();
let meterTypeId = computed(() => {
  return props.meterType === "water"
    ? 1
    : props.meterType === "electricity"
      ? 2
      : 3;
});

let meterIdArray = ref([]);

async function getMeterIdArray() {
  if (props.meterId) {
    meterIdArray.value = [props.meterId];
  } else {
    meterIdArray.value = (
      await getFirstLevelMeterList({
        company_id: companyStore.currentCompany.id,
        type: meterTypeId.value,
      })
    ).map((item) => item.id);
  }
}

watchEffect(async () => {
  try {
    await getMeterIdArray();
    await fetchData();
  } catch (error) {
    handleError(error, "获取数据失败");
  } finally {
    loading.value = false;
  }
});

async function fetchData() {
  if (!meterIdArray.value.length) {
    return;
  }
  loading.value = true;

  const allRangeData = await Promise.all(
    props.dateRange.map(async (range) => {
      const rangeData = await Promise.all(
        meterIdArray.value.map((id) => {

          return getMeterReportApi({
            id: id,
            interval: props.interval,
            start_time: range.start_time,
            end_time: range.end_time,
          });
        })
      );


      return {
        legend: range.legend,
        data: processArrays(rangeData.map((item) => item.aggregated_data)),
      };
    })
  );

  setChartOption(allRangeData);
}
function formatChartData(data) {
  let formatData = "HH:mm";
  switch (props.interval) {
    case "half_hour":
      formatData = "HH:mm";
      break;
    case "day":
      // 如果是对比周数据，转换为周几的格式
      if (props.dateRange.some((range) => range.legend.includes("周"))) {
        return data.map((item) => {
          const date = dayjs(item.end_time);
          const weekDay = ["日", "一", "二", "三", "四", "五", "六"][
            date.day()
          ];
          return {
            time: `周${weekDay}`,
            value: item.Value,
          };
        });
      }
      formatData = "YYYY-MM-DD";
      break;
    case "month":
      // 自定义月份格式化
      return data.map((item) => {
        const date = dayjs(item.start_time);
        return {
          time: `${date.month() + 1}月`,
          value: item.Value,
        };
      });
    default:
      break;
  }
  return data.map((item) => {
    return {
      time: dayjs(item.end_time).format(formatData),
      value: item.Value,
    };
  });
}

function setChartOption(allRangeData) {
  if (!allRangeData.length || !allRangeData[0].data.length) {
    chartOption.value = {};
    return;
  }

  const formattedData = allRangeData.map((range) => ({
    legend: range.legend,
    data: formatChartData(range.data),
  }));

  chartOption.value = {
    yAxisUnit: props.meterType === "electricity" ? "kWh" : "m³",
    xAxisData: formattedData[0].data.map((item) => item.time),
    series: formattedData.map((range, index) => ({
      name: range.legend,
      data: range.data.map((item) => item.value),
      type: props.chartType,
    })),
    customColors: generateColors(formattedData.length),
    showMarkLine: true,
  };
}

function generateColors(count) {
  const baseColors = ["#7dafff", "#409EFF", "#87CEEB", "#4169E1", "#1E90FF"];
  return baseColors.slice(0, count);
}
</script>

<style scoped>
.chart-wrapper {
  width: 100%;
  height: 100%;
}

:deep(.echarts-wrapper) {
  flex: 1;
  min-height: 0;
}
</style>
